package cn.edu.zsc.study;

import cn.edu.zsc.study.entity.*;
import cn.edu.zsc.study.repository.DeptRepository;
import cn.edu.zsc.study.repository.UserRepository;
import cn.edu.zsc.study.repository.UserRolesReposity;
import cn.edu.zsc.study.service.RoleService;
import cn.edu.zsc.study.service.UserService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统初始化程序
 *
 * @author harry_yao
 */
@AllArgsConstructor
@Component
@Profile("!test")
public class FirstTimeInitializer implements CommandLineRunner {

    private final UserRepository userRepo;
    private final DeptRepository deptRepo;
    private final UserService userService;
    private final RoleService roleService;
    private final UserRolesReposity urService;
    private final PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) {
        Dept dept = null;
        User admin = null;
        if (userRepo.selectCount(null) == 0L) {
            Role adminRole = new Role();
            adminRole.setName("管理员");
            adminRole.setAuthorities(new HashSet<>(Arrays.asList(Authority.values())));
            Role normalRole = new Role();
            normalRole.setName("普通用户");
            normalRole.setAuthorities(new HashSet<>(
                    Arrays.asList(
                            Authority.DEPT_QUERY,
                            Authority.USER_QUERY,
                            Authority.ROLE_QUERY
                    )
            ));
            roleService.save(adminRole);
            roleService.save(normalRole);
            Dept tmp = new Dept();
            tmp.setName("管理部门");
            deptRepo.insert(tmp);
            dept = deptRepo.selectById(tmp.getId());
            admin = new User(
                    "admin",
                    passwordEncoder.encode("admin"),
                    "15913375741",
                    "admin@test.dl.com",
                    true,
                    dept.getId(),
                    null,
                    null,
                    null);
            userService.save(admin);
            urService.insert(new UserRole(admin.getId(), adminRole.getId()));
        }
    }



}
